package main.users;

import main.FactageApp;
import main.components.GradientPanel;

import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.LineBorder;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
import java.awt.*;
import java.awt.event.*;

public class NewPasswordDialog {
    private JDialog dlg;
    private JPasswordField inputPassword, inputPassword1;
    private char passwordChar;
    private Border defaultBorder;
    private JButton okButton;
    private JLabel errorLabel;

    public NewPasswordDialog() {
        initComponents();
    }

    private void initComponents() {
        dlg = new JDialog();
        dlg.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
        dlg.setLayout(new GridBagLayout());
        dlg.setTitle("Изменение пароля");
        dlg.setResizable(true);
        dlg.setType(java.awt.Window.Type.UTILITY);
        dlg.setModal(true);

        //region Инициализация шапки
        GradientPanel headerPanel = new GradientPanel(new GridBagLayout(), new Color(140, 250, 156), new Color(99, 176, 111));
        JLabel headerLabel = new JLabel("Изменение пароля пользователя");
        headerLabel.setFont(new Font("Segoe UI", 0, 18));
        headerLabel.setForeground(Color.WHITE);
        dlg.add(headerPanel, new GridBagConstraints(0, 0, 3, 1, 0.1, 0.1, GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
        headerPanel.add(headerLabel, new GridBagConstraints(0, 0, 1, 1, 0.5, 0, GridBagConstraints.WEST, GridBagConstraints.WEST, new Insets(30, 56, 7, 56), 0, 0));
        //endregion

        dlg.add(new JLabel("<html>Ваш пароль соответствует логину и является временным.<br/>Для работы с системой задайте, пожалуйста, новый пароль.<br/><br/><i>Повторно пароль необходимо ввести для исключения ошибки при наборе.</i></html>"), new GridBagConstraints(0, 1, 3, 1, 0, 0.1, GridBagConstraints.NORTHEAST, GridBagConstraints.NONE, new Insets(31, 56, 0, 56), 0, 0));
        dlg.add(new JLabel("Пароль"), new GridBagConstraints(0, 2, 1, 1, 0, 0.1, GridBagConstraints.NORTHEAST, GridBagConstraints.NONE, new Insets(22, 56, 0, 0), 0, 0));
        dlg.add(new JLabel("Повторно пароль"), new GridBagConstraints(0, 3, 1, 1, 0, 0.1, GridBagConstraints.NORTHEAST, GridBagConstraints.NONE, new Insets(22, 56, 0, 0), 0, 0));

        inputPassword = new JPasswordField("Ваш пароль");
        passwordChar = inputPassword.getEchoChar();
        inputPassword.setEchoChar((char) 0);
        inputPassword.setForeground(Color.gray);
        inputPassword.setPreferredSize(new Dimension(180, 22));
        inputPassword.addFocusListener(new FocusListener() {
            @Override
            public void focusGained(FocusEvent focusEvent) {
                inputPassword.setForeground(Color.black);
                if (new String(inputPassword.getPassword()).equals("Ваш пароль")) {
                    inputPassword.setEchoChar(passwordChar);
                    inputPassword.setText("");
                }
            }

            @Override
            public void focusLost(FocusEvent focusEvent) {
                if (new String(inputPassword.getPassword()).equals("")) {
                    inputPassword.setEchoChar((char) 0);
                    inputPassword.setForeground(Color.gray);
                    inputPassword.setText("Ваш пароль");
                }

            }
        });
        inputPassword.addCaretListener(new CaretListener() {
            @Override
            public void caretUpdate(CaretEvent caretEvent) {
                comparePasswords();
            }
        });
        inputPassword.addKeyListener(new KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
                    inputPassword1.requestFocus();
                }
            }
        });
        dlg.add(inputPassword, new GridBagConstraints(1, 2, 1, 1, 0, 0.1, GridBagConstraints.NORTHWEST, GridBagConstraints.WEST, new Insets(18, 8, 0, 56), 0, 0));

        inputPassword1 = new JPasswordField("Ваш пароль еще раз");
        inputPassword1.setPreferredSize(new Dimension(180, 22));
        inputPassword1.setEchoChar((char) 0);
        inputPassword1.setForeground(Color.gray);
        defaultBorder = inputPassword1.getBorder();
        inputPassword1.addFocusListener(new FocusListener() {
            @Override
            public void focusGained(FocusEvent focusEvent) {
                inputPassword1.setForeground(Color.black);
                if (new String(inputPassword1.getPassword()).equals("Ваш пароль еще раз")) {
                    inputPassword1.setEchoChar(passwordChar);
                    inputPassword1.setText("");
                }
            }

            @Override
            public void focusLost(FocusEvent focusEvent) {
                if (new String(inputPassword1.getPassword()).equals("")) {
                    inputPassword1.setEchoChar((char) 0);
                    inputPassword1.setForeground(Color.gray);
                    inputPassword1.setText("Ваш пароль еще раз");
                }

            }
        });
        inputPassword1.addCaretListener(new CaretListener() {
            @Override
            public void caretUpdate(CaretEvent caretEvent) {
                comparePasswords();
            }
        });
        inputPassword1.addKeyListener(new KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                if (evt.getKeyCode() == KeyEvent.VK_ENTER) {

                    String password, password1;
                    password = String.valueOf(inputPassword.getPassword());
                    password1 = String.valueOf(inputPassword1.getPassword());

                    if (!password.equals("Ваш пароль") && !password1.equals("Ваш пароль еще раз") && password.equals(password1)) {
                        updatePassword();
                    } else {
                        if (password.equals("Ваш пароль") || password.equals("")) {
                            errorLabel.setText("Пароль не может быть пустым.");
                            inputPassword.setBorder( new LineBorder(Color.red, 1));
                        }
                        if ( password1.equals("Ваш пароль еще раз") || password1.equals("")) {
                            errorLabel.setText("Пароль не может быть пустым.");
                            inputPassword1.setBorder( new LineBorder(Color.red, 1));
                        }
                        if (!password.equals(password1)) {
                            errorLabel.setText("Введены разные пароли.");
                            inputPassword1.setBorder( new LineBorder(Color.red, 1));
                        }

                        dlg.add(errorLabel, new GridBagConstraints(1, 4, 1, 1, 0, 0.1, GridBagConstraints.NORTHWEST, GridBagConstraints.WEST, new Insets(18, 8, 0, 0), 0, 0));
                        dlg.pack();
                        dlg.repaint();
                        System.out.println("fuck you!");
                    }
                }
            }
        });
        dlg.add(inputPassword1, new GridBagConstraints(1, 3, 1, 1, 0, 0.1, GridBagConstraints.NORTHWEST, GridBagConstraints.WEST, new Insets(18, 8, 0, 56), 0, 0));

        errorLabel = new JLabel("Empty password");
        errorLabel.setForeground(Color.red);

        okButton = new JButton("Изменить");
        okButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                updatePassword();
            }
        });
        okButton.setPreferredSize(new Dimension(90, 24));
        okButton.setEnabled(false);
        dlg.add(okButton, new GridBagConstraints(1, 5, 2, 1, 0, 50, GridBagConstraints.NORTHWEST, GridBagConstraints.WEST, new Insets(18, 8, 30, 0), 0, 0));

        dlg.pack();

        Dimension screensize = Toolkit.getDefaultToolkit().getScreenSize();
        dlg.setLocation(screensize.width / 2 - dlg.getWidth() / 2, screensize.height / 2 - dlg.getHeight() / 2);

        dlg.setVisible(true);
    }

    private void updatePassword() {
        FactageApp.user.updatePassword(String.valueOf(inputPassword.getPassword()));
        dlg.dispose();
    }

    private void comparePasswords() {
        String password, password1;
        password = String.valueOf(inputPassword.getPassword());
        password1 = String.valueOf(inputPassword1.getPassword());

        if (!password.equals("Ваш пароль") && !password1.equals("Ваш пароль еще раз") && password.equals(password1)) {

            dlg.remove(errorLabel);
            inputPassword.setBorder(defaultBorder);
            inputPassword1.setBorder(defaultBorder);
            okButton.setEnabled(true);
            dlg.pack();
            dlg.repaint();

        } else if (password.equals("Ваш пароль") || password1.equals("Ваш пароль еще раз") || !password.equals(password1)) {
            okButton.setEnabled(false);
        }

    }

}
